package com.jt.controller;

import com.jt.pojo.User;
import com.jt.service.UserService;
import com.jt.vo.PageResult;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 用户登录
    @PostMapping("/login")
    public SysResult loginByUP(@RequestBody User user){
        String token = userService.loginByUP(user);
        if(token == null || "".equals(token)){
            return SysResult.fail();
        }else {
            return SysResult.success(token);
        }
    }

    // 用户注册
    @PostMapping("/register")
    public SysResult register(@RequestBody User user){
        String msg = userService.register(user);
        if(msg == null || "".equals(msg)){
            return SysResult.success();
        }
        return SysResult.fail(msg);

    }

    // 密码修改
    @PutMapping("/update")
    public SysResult updateByUn(@RequestBody User user){
        String msg = userService.updateByUn(user);
        if(msg == null || "".equals(msg)){
            return SysResult.success();
        }
        return SysResult.fail(msg);
    }

    // 分页查询用户信息
    @GetMapping("/list")
    public SysResult getUserListByPage(PageResult pageResult){
        pageResult = userService.getUserListByPage(pageResult);
        return SysResult.success(pageResult);
    }

    // 根据ID修改用户状态
    @PutMapping("/status/{id}/{status}")
    public SysResult updateStatusById(User user){
        String msg = userService.updateStatusById(user);
        if (null == msg){
            return SysResult.success();
        }
        return SysResult.fail(msg);

    }

    /*
    * 修改用户昵称，邮箱，电话
    * 分为下面两步
    * */
    // 1.根据ID查询用户信息
    @GetMapping("/{id}")
    public SysResult findUserById(@PathVariable Integer id){
        User user = userService.findUserById(id);
        return SysResult.success(user);
    }

    // 2.根据Id修改用户昵称、电话和邮箱
    @PutMapping("updateUser")
    public SysResult updateUser(@RequestBody User user){
        String msg = userService.updateUser(user);
        if (msg == null){
            return SysResult.success();
        }
        return SysResult.fail(msg);

    }

    // 根据id删除用户
    @DeleteMapping("/{id}")
    public SysResult deleteUser(@PathVariable Integer id){
        try {
            userService.deleteUser(id);
            return SysResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return SysResult.fail();
        }
    }

}
